import Glibc
class Timer {
    private let CLOCK_REALTIME = 0
    private var start_timespec = timespec()
    private var end_timespec = timespec()
    private var time_spec = timespec()
    func start() {
        clock_gettime(Int32(CLOCK_REALTIME),&start_timespec)
    }
    
    func stop() -> Double {
        clock_gettime(Int32(CLOCK_REALTIME),&end_timespec)
        let start_time = Double(start_timespec.tv_sec * 1_000_000 + start_timespec.tv_nsec / 1_000)
        let end_time = Double(end_timespec.tv_sec * 1_000_000 + end_timespec.tv_nsec / 1_000)
        let time = end_time - start_time
        return time / 1_000
    }
    func getTime() -> Double {
        clock_gettime(Int32(CLOCK_REALTIME),&time_spec)
        return Double(time_spec.tv_sec * 1_000_000 + time_spec.tv_nsec / 1_000)
    }
}

let timer = Timer()
var global = 0.0

func partial(_ n: Int) -> Double {
    var a1: Double = 0.0
    var a2: Double = 0.0
    var a3: Double = 0.0
    var a4: Double = 0.0
    var a5: Double = 0.0
    var a6: Double = 0.0
    var a7: Double = 0.0
    var a8: Double = 0.0
    var a9: Double = 0.0
    let twothirds: Double = 2.0 / 3.0
    var alt: Double = -1.0
    var k2: Double = 0.0
    var k3: Double = 0.0
    var sk: Double = 0.0
    var ck: Double = 0.0

    for k in 1...n {
        k2 = Double(k * k)
        k3 = k2 * Double(k)
        sk = sin(Double(k))
        ck = cos(Double(k))
        alt = -alt

        a1 += pow(twothirds, Double(k - 1))
        a2 += pow(Double(k), -0.5)
        a3 += 1.0 / (Double(k) * (Double(k) + 1.0))
        a4 += 1.0 / (k3 * sk * sk)
        a5 += 1.0 / (k3 * ck * ck)
        a6 += 1.0 / Double(k)
        a7 += 1.0 / k2
        a8 += alt / Double(k)
        a9 += alt / (2.0 * Double(k) - 1.0)
    }

    return a6 + a7 + a8 + a9
}

func runPartialSum() -> Int {
    var res: Double = 0.0
    var i = 1024
    timer.start()
    while i <= 16384 {
        res += partial(i)
        i *= 2
    }
    let time = timer.stop()
    global = res
    // XCTAssertEqual(res, 0.4145028187500179)
    print("Numerical Calculation - RunPartialSum:\t"+String(time)+"\tms");
    return Int(time)
}

_ = runPartialSum()
print("PartialSum Is End , global value is \(global)")
// print(runPartialSum())